<template>
  <div class="product-detail">
    <header-nav />
    
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>全部商品</el-breadcrumb-item>
        <el-breadcrumb-item>{{ product?.name }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>
    
    <template v-else>
      <div class="product-container">
        <!-- 商品图片 -->
        <div class="product-gallery">
          <div class="main-image">
            <el-image 
              :src="product.image" 
              :alt="product.name"
              fit="contain"
            />
          </div>
          <div class="thumbnail-list">
            <el-image 
              v-for="i in 3" 
              :key="i"
              :src="product.image" 
              fit="cover"
              class="thumbnail"
            />
          </div>
        </div>
        
        <!-- 商品信息 -->
        <div class="product-info">
          <h1 class="product-name">{{ product.name }}</h1>
          
          <!-- 评分区域 -->
          <div class="rating-section">
            <el-rate
              v-model="reviewStats.averageRating"
              disabled
              show-score
              text-color="#ff9900"
            />
            <span class="review-count">{{ reviewStats.totalCount }}条评价</span>
          </div>

          <!-- 价格区域 -->
          <div class="price-section">
            <div class="current-price">
              <span class="currency">¥</span>
              <span class="amount">{{ Number(product.price).toFixed(2) }}</span>
            </div>
            <div class="sales-info">
              <span>销量: {{ product.sales }}</span>
              <span>库存: {{ product.stock }}</span>
            </div>
          </div>

          <!-- 规格选择 -->
          <div class="specs-section">
            <div class="spec-title">选择规格</div>
            <el-select v-model="selectedSize" placeholder="选择尺寸" class="spec-select">
              <el-option label="小号" value="small" />
              <el-option label="中号" value="medium" disabled />
              <el-option label="大号" value="large" />
            </el-select>
          </div>
          
          <!-- 购买按钮 -->
          <div class="action-buttons">
            <el-button type="primary" size="large" class="notify-btn" @click="handleNotify">
              到货通知
            </el-button>
            <el-button 
              type="danger" 
              plain 
              size="large" 
              class="wishlist-btn"
              :icon="isFavorite ? 'Star' : 'StarFilled'"
              @click="handleToggleFavorite"
            >
              {{ isFavorite ? '已收藏' : '加入心愿单' }}
            </el-button>
          </div>


        </div>
      </div>

      <!-- 商品详情标签页 -->
      <div class="product-tabs">
        <el-tabs v-model="activeTab" class="demo-tabs">
          <el-tab-pane label="商品详情" name="details">
            <div class="details-content">
              <p>{{ product.description }}</p>
              <div class="safety-guide">
                <h3>安全指南</h3>
                <ul>
                  <li>适用年龄：3岁以上</li>
                  <li>材质：优质毛绒面料</li>
                  <li>清洗方式：手洗或机洗</li>
                  <li>注意事项：请勿接触明火</li>
                </ul>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="商品评价" name="reviews">
            <div class="reviews-section">
              <div class="reviews-summary">
                <div class="rating-overview">
                  <div class="average-rating">
                    <span class="rating-number">{{ reviewStats.averageRating }}</span>
                    <el-rate v-model="reviewStats.averageRating" disabled />
                  </div>
                  <div class="rating-count">
                    共 {{ reviewStats.totalCount }} 条评价
                  </div>
                </div>
                <el-button type="primary" @click="handleWriteReview">
                  写评价
                </el-button>
              </div>

              <div v-if="reviews.length > 0" class="reviews-list">
                <div v-for="review in reviews" :key="review.id" class="review-item">
                  <div class="review-header">
                    <h3>{{ review.title }}</h3>
                    <el-rate v-model="review.rating" disabled />
                  </div>
                  <p class="review-meta">
                    {{ review.username }} · {{ formatDate(review.created_at) }}
                  </p>
                  <p class="review-content">{{ review.content }}</p>
                </div>
              </div>
              <div v-else class="no-reviews">
                暂无评价
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="AI 故事" name="story">
          <!-- 故事生成按钮和展示区域 -->
          <div class="story-section">
            <el-button 
              type="primary" 
              :loading="generatingStory"
              @click="generateStory"
            >
              生成玩具故事
            </el-button>
            
            <div v-if="story" class="story-content">
              <h3>玩具的奇妙故事</h3>
              <p style="white-space: pre-line">{{ story }}</p>
            </div>
          </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 评论对话框 -->
      <review-dialog
        v-if="product"
        v-model:visible="reviewDialogVisible"
        :product="product"
        @submitted="handleReviewSubmitted"
      />
    </template>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, inject } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import HeaderNav from '../components/HeaderNav.vue'
import axios from '../utils/axios'
import { Platform } from '@element-plus/icons-vue'
import ReviewDialog from '../components/ReviewDialog.vue'

const route = useRoute()
const router = useRouter()
const loading = ref(true)
const product = ref(null)
const activeTab = ref('details')
const selectedSize = ref('')
const story = ref('')
const generatingStory = ref(false)
const reviews = ref([])
const reviewStats = ref({
  totalCount: 0,
  averageRating: 0
})
const reviewDialogVisible = ref(false)
const isFavorite = ref(false)
const headerNavMethods = inject('headerNavMethods')

const fetchProduct = async () => {
  try {
    loading.value = true
    const { data } = await axios.get(`/api/products/${route.params.id}`)
    product.value = data
    
    // 记录浏览历史
    if (data && data.id) {
      await recordProductView(data.id);
    }
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('获取商品信息失败')
  } finally {
    loading.value = false
  }
}

const generateStory = async () => {
  if (!product.value?.name) return
  
  try {
    generatingStory.value = true
    story.value = '' // 清空之前的故事
    
    console.log('正在请求故事生成，玩具名称:', product.value.name)
    
    const response = await axios.post('/api/story/generate', {
      toyName: product.value.name
    }, {
      timeout: 60000 // 增加超时时间到60秒
    })
    
    console.log('故事生成响应:', response.data)
    
    if (response.data.success) {
      story.value = response.data.story
    } else {
      ElMessage.error(response.data.message || '故事生成失败')
    }
  } catch (error) {
    console.error('Error generating story:', error)
    
    // 更详细的错误处理
    if (error.response) {
      // 服务器返回了错误状态码
      console.error('服务器响应错误:', error.response.data)
      ElMessage.error(error.response.data.message || '故事生成失败，服务器返回错误')
    } else if (error.request) {
      // 请求发送成功，但没有收到响应
      console.error('未收到服务器响应')
      ElMessage.error('AI故事生成需要较长时间，请稍后重试')
    } else {
      // 请求设置时发生错误
      console.error('请求错误:', error.message)
      ElMessage.error('请求错误: ' + error.message)
    }
  } finally {
    generatingStory.value = false
  }
}

const fetchReviews = async () => {
  try {
    const { data } = await axios.get(`/api/products/${route.params.id}/reviews`)
    reviews.value = data.reviews
    reviewStats.value = data.stats
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('获取评论失败')
  }
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

const handleWriteReview = () => {
  reviewDialogVisible.value = true
}

const handleReviewSubmitted = () => {
  fetchReviews() // 重新获取评论列表
}

const handleNotify = () => {
  ElMessage.success('到货通知已设置')
}

const checkWishlistStatus = async () => {
  try {
    const { data } = await axios.get('/api/wishlist')
    isFavorite.value = data.some(item => item.id === Number(route.params.id))
  } catch (error) {
    console.error('Error:', error)
  }
}

const handleToggleFavorite = async () => {
  try {
    if (!isFavorite.value) {
      await axios.post(`/api/wishlist/${route.params.id}`)
      ElMessage.success('已添加到心愿单')
      isFavorite.value = true
    } else {
      await axios.delete(`/api/wishlist/${route.params.id}`)
      ElMessage.success('已从心愿单移除')
      isFavorite.value = false
    }
    
    // 确保 headerNavMethods 存在
    if (headerNavMethods) {
      await headerNavMethods.refreshWishlist()
    }
  } catch (error) {
    console.error('Error:', error)
    if (error.response?.status === 400) {
      ElMessage.warning(error.response.data.message)
    } else if (error.response?.status === 401) {
      ElMessage.error('请先登录')
      router.push('/login')
    } else {
      ElMessage.error('操作失败')
    }
  }
}

const handleAddToCart = async () => {
  try {
    await axios.post('/api/cart', {
      productId: route.params.id,
      quantity: quantity.value
    })
    ElMessage.success('已添加到购物车')
    await headerNavMethods.value.refreshCart()
  } catch (error) {
    console.error('Error:', error)
    if (error.response?.status === 401) {
      ElMessage.error('请先登录')
      router.push('/login')
    } else {
      ElMessage.error('添加失败')
    }
  }
}

const recordProductView = async (productId) => {
  try {
    await axios.post('/api/user/record-view', { productId });
    console.log('浏览记录已保存');
  } catch (error) {
    console.error('保存浏览记录失败:', error);
    // 这里不需要向用户显示错误，静默失败即可
  }
}

onMounted(() => {
  fetchProduct()
  fetchReviews()
  checkWishlistStatus()
})
</script>

<style scoped>
.product-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.breadcrumb {
  margin: 20px 0;
}

.product-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 60px;
  margin: 40px 0;
}

.product-gallery {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.main-image {
  border-radius: 12px;
  overflow: hidden;
  background: #fff;
  height: 500px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.main-image :deep(.el-image) {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.thumbnail-list {
  display: flex;
  gap: 10px;
}

.thumbnail {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.3s;
}

.thumbnail:hover {
  border-color: var(--el-color-primary);
}

.product-info {
  padding: 20px;
}

.product-name {
  font-size: 32px;
  margin-bottom: 20px;
  color: #333;
}

.rating-section {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.review-count {
  color: #666;
}

.price-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
}

.current-price {
  display: flex;
  align-items: baseline;
  margin-bottom: 10px;
}

.currency {
  font-size: 24px;
  color: #ff6b6b;
}

.amount {
  font-size: 36px;
  font-weight: bold;
  color: #ff6b6b;
}

.sales-info {
  display: flex;
  gap: 20px;
  color: #666;
}

.specs-section {
  margin-bottom: 30px;
}

.spec-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 10px;
}

.spec-select {
  width: 100%;
}

.action-buttons {
  display: flex;
  gap: 20px;
}

.notify-btn {
  flex: 2;
}

.wishlist-btn {
  flex: 1;
}

.product-tabs {
  margin: 40px 0;
}

.details-content {
  padding: 20px;
  line-height: 1.8;
}

.safety-guide {
  margin-top: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.safety-guide h3 {
  margin-bottom: 15px;
  color: #333;
}

.safety-guide ul {
  list-style: none;
  padding: 0;
}

.safety-guide li {
  margin: 10px 0;
  color: #666;
}

.reviews-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 30px;
}

.rating-overview {
  display: flex;
  align-items: center;
  gap: 30px;
}

.average-rating {
  text-align: center;
}

.rating-number {
  font-size: 36px;
  font-weight: bold;
  color: #ff9900;
}

.reviews-section {
  margin: 60px 0;
  padding: 0 20px;
}

.reviews-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.review-item {
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.review-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.review-meta {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
}

.review-content {
  color: #333;
  line-height: 1.6;
}

.no-reviews {
  text-align: center;
  padding: 40px;
  color: #666;
  background: #f9f9f9;
  border-radius: 8px;
}

.story-section {
  margin-top: 30px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.story-content {
  margin-top: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  line-height: 1.8;
}

.story-content h3 {
  color: #333;
  margin-bottom: 16px;
  font-size: 18px;
}

.story-content p {
  color: #666;
  text-indent: 2em;
  margin: 0;
}

@media (max-width: 768px) {
  .product-container {
    grid-template-columns: 1fr;
    gap: 30px;
  }

  .main-image {
    height: 300px;
  }

  .product-name {
    font-size: 24px;
  }

  .action-buttons {
    flex-direction: column;
  }
}
</style> 